package com.example.JavaWebApi.core.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.function.Consumer;
import java.util.function.Function;

@Slf4j
@Component
@Conditional(value = {MqttCondition.class})
public class MqttConfig {
    @Autowired
    private MqttConfiguration mqttConfiguration;
    private MqttClient client;
    @PostConstruct
    public void connect(){
        client=getClient(mqttConfiguration.getClientid());
    }
    /**
     * 客户端连接服务端
     */
    public MqttClient getClient(String clientId){
        try{
            //创建MQTT客户端对象
            MqttClient client = new MqttClient(mqttConfiguration.getHost(),clientId,new MemoryPersistence());
            //连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            //是否清空session，设置false表示服务器会保留客户端的连接记录（订阅主题，qos）,客户端重连之后能获取到服务器在客户端断开连接期间推送的消息
            //设置为true表示每次连接服务器都是以新的身份
            options.setCleanSession(true);
            //设置连接用户名
            options.setUserName(mqttConfiguration.getUsername());
            //设置连接密码
            options.setPassword(mqttConfiguration.getPassword().toCharArray());
            //设置超时时间，单位为秒
            options.setConnectionTimeout(100);
            //设置心跳时间 单位为秒，表示服务器每隔 1.5*20秒的时间向客户端发送心跳判断客户端是否在线
            options.setKeepAliveInterval(20);
            //设置遗嘱消息的话题，若客户端和服务器之间的连接意外断开，服务器将发布客户端的遗嘱信息
            options.setWill("willTopic",(mqttConfiguration.getClientid() + "与服务器断开连接").getBytes(),0,false);
            //设置回调
            //client.setCallback(this);
            client.connect(options);
            return client;
        } catch(MqttException e){
            throw new RuntimeException(e);
        }
    }
    public void publish(int qos,boolean retained,String topic,String message){
        publish(topic,mqttMessage->{
            mqttMessage.setQos(qos);
            mqttMessage.setRetained(retained);
            mqttMessage.setPayload(message.getBytes());
        });
    }
    public void publish(int qos,boolean retained,String topic,byte[] message){
        publish(topic,mqttMessage->{
            mqttMessage.setQos(qos);
            mqttMessage.setRetained(retained);
            mqttMessage.setPayload(message);
        });
    }
    private void publish(String topic,Consumer<MqttMessage> consumer){
        MqttMessage mqttMessage = new MqttMessage();
        consumer.accept(mqttMessage);
        MqttTopic mqttTopic = client.getTopic(topic);
        //提供一种机制来跟踪消息的传递进度
        //用于在以非阻塞方式（在后台运行）执行发布是跟踪消息的传递进度
        MqttDeliveryToken token;
        try {
            //将指定消息发布到主题，但不等待消息传递完成，返回的token可用于跟踪消息的传递状态
            //一旦此方法干净地返回，消息就已被客户端接受发布，当连接可用，将在后台完成消息传递。
            token = mqttTopic.publish(mqttMessage);
            token.waitForCompletion();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
//    public void subscribe(MqttClient client,String topic,MqttCallback callback) throws MqttException {
//        client.subscribe(topic);
//        client.setCallback(callback);
//        log.info("已经订阅主题{},处理者{}",topic,callback.getClass().getName());
//    }
}
